package com.liuwei.spring.cloud.junit.leetcode.array;

import lombok.extern.slf4j.Slf4j;

/**
 * https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/description/?envType=study-plan-v2&envId=top-interview-150
 */
@Slf4j
public class RemoveDuplicates {

    /**
     * 给你一个有序数组 nums ，请你 原地 删除重复出现的元素，使得出现次数超过两次的元素只出现两次 ，返回删除后数组的新长度
     * @param args
     */
    public static void main(String[] args) {
        RemoveDuplicates instance = new RemoveDuplicates();
        int[] nums = {0,1,1,2,2,3};
        //int[] nums = {1,1,1,2,2,3};
        //int[] nums = {0,0,1,1,1,1,2,3,3};
        int result = instance.removeDuplicates(nums);
        log.info("total {}", result);
    }

    public int removeDuplicates(int[] nums) {
        Integer lastValue = null;
        int lastCount = 0;
        for (int i = 0; i < nums.length; i++) {
            //log.info("index:{} nums {}", i,nums);
            int tempValue = nums[i];
            if (tempValue==Integer.MIN_VALUE) {
                return i;
            }
            if(lastValue==null){
                lastValue = tempValue;
                lastCount = 1;
                continue;
            }
            if(tempValue!=lastValue){
                lastValue = tempValue;
                lastCount = 1;
                continue;
            }
            lastCount++;
            if (lastCount ==2) {
                while(i+1<nums.length && nums[i+1]==lastValue){
                    moveForward(nums, i+1);
                }
            }
        }
        return nums.length;
    }

    private void moveForward(int[] nums,int i){
        for (int j = i+1; j < nums.length; j++) {
            nums[j-1] = nums[j];
        }
        nums[nums.length-1] = Integer.MIN_VALUE;
    }
}
